import os
import time
import urllib3
import json
import shutil
import requests
import zipfile
import notify
import deploy_level
import cdn_refresh

def save_level_param(param):
    cwd = os.getcwd()
    with open(os.path.join(cwd, "level.json"), "w") as f:
        f.write(param)

def load_level_card():
    cwd = os.getcwd()
    level = os.path.join(cwd, "level.json")

    rindex = []
    with open(level, "r") as fr:
        content = fr.read()
        strip = content.strip()
        lines = strip.split(",")
        
        for key in lines:
            if (key.find("-") > 0):
                rline = key.split("-")
                rstart = int(rline[0])
                rend = int(rline[1])

                for i in range(rstart, rend + 1):
                    rindex.append(i)
            else:
                rindex.append(int(key))
        print("levels:" + str(rindex))
        
    return rindex

def download_level_config(url_config, testconfigs, android_localpath, ios_localpath):
    http = urllib3.PoolManager()
    levelconfig = []
    for key in testconfigs:
        print("=================================")
        print(key)

        with open(key, "rb") as freader:
            data = json.load(freader)
            assetname =  data["path"].replace("level", "")
            levelurl =  url_config["TEST"]["level_url"] + assetname

            savepath = None
            if "Android" in key:
                savepath = android_localpath + assetname
            elif "iOS" in key:
                savepath = ios_localpath + assetname
            
            r = http.request('GET', levelurl)
            if r.status == 200:
                print("save path " + savepath)
                with open(savepath, "wb") as fwriter:
                    fwriter.write(r.data)
                    fwriter.flush()
                configpath = savepath.replace(".zip", "")
                with zipfile.ZipFile(savepath, 'r') as zipf:
                    zipf.extractall(configpath)   
                levelconfig.append(os.path.join(configpath, "ThemesAssetsConfig.json"))
    return levelconfig

def sync_level_to_release(param, url_config, request_configs, context):
    save_level_param(param)

    cwd = os.getcwd()

    test = url_config["TEST"]
    testdir = os.path.join(cwd, "temp/" + test["local_dir"])
    print("temp dir " + testdir)
    if os.path.exists(testdir):
        shutil.rmtree(testdir)
    os.mkdir(testdir)

    android_localpath = os.path.join(testdir, "Android")
    ios_localpath = os.path.join(testdir, "iOS")
    os.mkdir(android_localpath)
    os.mkdir(ios_localpath)

    config = {"CF_AndroidThemesAssets", "CF_iOSThemesAssets",}
    testconfigs = request_configs(test, testdir, "list", config)
    print("configs: " + str(testconfigs))

    levels = load_level_card()

    if len(levels) == 0:
        context["Status"]="deploy assets is null"
        notify.push_result(context)
        exit(0)

    levelconfig = download_level_config(url_config, testconfigs, android_localpath, ios_localpath)
    if (len(levelconfig) == 0):
        context["Status"]="deploy assets download zip fail"
        notify.push_result(context)
        exit(0)

    check_assets = []
    sync_assets = []
    for key in testconfigs:
        print("=================================")
        print(key)

        with open(key, "rb") as freader:
            data = json.load(freader)
            assetname =  data["path"].replace("level/", "")
            sync_assets.append(assetname)
            check_assets.append(assetname)

    for key in levelconfig:
        print("=================================")
        print(key)

        with open(key, "rb") as freader:
            data = json.load(freader)

            platform = None
            if "Android" in key:
                platform = "Android"
            elif "iOS" in key:
                platform = "iOS"

        for i in levels:
            item = data[i - 1]
            if item == None:
                print("data[i] not exist level:" + i)
                context["Status"]="deploy level not exist"
                notify.push_result(context)
                exit(0)
            sync_assets.append(platform + "/levels/" + str(i) + "/")
            for (k, v) in item.items():
                print("key: " + k  + ", value: " + str(v))
                if k == "dice":
                    continue
                if k == "island":
                    islad = platform + "/levels/" +  v["path"]
                    if islad in sync_assets:
                        continue
                    sync_assets.append(islad)
                    check_assets.append(islad)
                else:
                    check_assets.append(platform + "/levels/" + str(i) + "/" +  v["path"])

    print("sync assets:\n" + str(sync_assets))
    deploy_level.deploy(sync_assets, context)

    time.sleep(10)
    cdnurls = check_level_assets(check_assets, url_config, context)

    # push cdn
    cdn_refresh.push(cdnurls)

def check_level_assets(check_assets, url_config, context):
    print("check_level_assets:")

    cdnurls = []
    awscdn = url_config["AWSCDN"]
    aliyuncdn = url_config["AliyunCDN"]

    result = []
    for key in check_assets:
        assetUrl = url_config["RELEASE"]["level_url"] + "/" + key
        aliyunUrl = assetUrl.replace(awscdn, aliyuncdn)
        cdnurls.append(aliyunUrl)

        r = requests.get(aliyunUrl, stream=True)
        print(aliyunUrl + "  status_code:" + str(r.status_code))
        if r.status_code != 200:
            result.append(key)

    if len(result) > 0:
        print("check level fail:\n " + str(result))
        context["Status"] = "sync_level_assets Fail"
    else:
        print("check level success")
        context["Status"] = "sync_level_assets Success"
    notify.push_result(context)
    return cdnurls